//
//  SSNewFeatureCollectionViewController.swift
//  MyMicroBlog
//
//  Created by stevenSu on 15/7/30.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class SSNewFeatureCollectionViewController: UICollectionViewController {
    private let pageCount = 4
    private let layout = NewFlowLayout()

    init() {
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(NewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pageCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewCell
        cell.index = indexPath.item
    
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        let currentIndexPath = collectionView.indexPathsForVisibleItems().last
        if let currentPath = currentIndexPath where currentIndexPath?.item == (pageCount - 1) {
            let cell = collectionView.cellForItemAtIndexPath(currentPath) as! NewCell
            cell.startAnimation()
        }
        
    }
    
    class NewCell: UICollectionViewCell {
        private let buttonBottomMargin: CGFloat = -160
        private lazy var iconView = UIImageView()
        private lazy var button: UIButton = {
            let btn = UIButton()
            btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
            btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
            btn.setTitle("马上体验", forState: UIControlState.Normal)
            btn.addTarget(self, action: "startClick", forControlEvents: UIControlEvents.TouchUpInside)
            
            return btn
        }()
        
        private var index = 0 {
            didSet {
                iconView.image = UIImage(named: "new_feature_\(index + 1)")
                button.hidden = true
            }
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupUI()
        }

        required init?(coder aDecoder: NSCoder) {
//            fatalError("init(coder:) has not been implemented")
            super.init(coder: aDecoder)
            setupUI()
        }
        
        func startClick() {
            NSNotificationCenter.defaultCenter().postNotificationName(SSRootControllerSwitchNotification, object: true)
        }
        
        private func startAnimation() {
            button.transform = CGAffineTransformMakeScale(0, 0)
            button.userInteractionEnabled = false
            button.hidden = false
            UIView.animateWithDuration(SSWelcomeViewControllerAnimationDuration * 0.5, delay: 0, usingSpringWithDamping: SSWelcomeViewControllerSpringDamping, initialSpringVelocity: SSWelcomeViewControllerSpringVelocity * 2, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                self.button.transform = CGAffineTransformIdentity
                }) { (_) -> Void in
                    self.button.userInteractionEnabled = true
            }
        }
        
        private func setupUI() {
            contentView.addSubview(iconView)
            contentView.addSubview(button)
            
            iconView.translatesAutoresizingMaskIntoConstraints = false
            contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": iconView]))
            contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": iconView]))
            
            button.translatesAutoresizingMaskIntoConstraints = false
            contentView.addConstraint(NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
            contentView.addConstraint(NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: buttonBottomMargin))
        }
    }
    
    class NewFlowLayout: UICollectionViewFlowLayout {
        override func prepareLayout() {
            itemSize = collectionView!.bounds.size
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            collectionView!.pagingEnabled = true
            collectionView!.showsHorizontalScrollIndicator = false
            collectionView!.bounces = false
        }
    }
}
